from databases.alchemy import Alchemy
class Postgres(Alchemy):

    def __init__(self, config):
       Alchemy.__init__(self, config)

    def format_change_column(self, table, column_name, attributes):
        string = ""
        if "default" in attributes:
            string = self._build_remainder(attributes)
        else:
            string = self._build_column_type(attributes)

        if not "DEFAULT" in string:
            string = "TYPE %s" % string
        else:
            string = "SET %s" % string

        return "ALTER TABLE %s ALTER COLUMN %s %s;" \
            % (table, column_name, string)

    def format_create_table(self, table, query):
        table_description, columns_description, primary_key = self._build_table(query)
        return "CREATE TABLE %s ( %s %s );" \
            % (table, self._columns(columns_description), self._primary_key(table, primary_key))

    def format_remove_index(self, table, index_name):
        return "DROP INDEX %s;" \
            % (index_name)

    def format_rename_column(self, table, column_name, new_name, attributes):
        return None

    def format_rename_table(self, table, new_name):
        return "ALTER TABLE %s RENAME TO %s;" \
            % (table, new_name)

    def _primary_key(self, table, primary_key):
        if not primary_key == "":
            if "," in primary_key:
                return ", CONSTRAINT %s_pk PRIMARY KEY (%s)" % (table, primary_key)
            else:
                return ", PRIMARY KEY (%s)" % (primary_key)
        else:
            return ""

    def _using(self, attributes):
        string = ""
        if 'using' in attributes:
            string = "USING %s" % attributes['using'].upper()

        return string

    def _build_remainder(self, attributes):
        string = ""
        if 'not_null' in attributes and attributes['not_null'].lower() == 'true':
            string = "%s NOT NULL" % string

        if 'default' in attributes and not attributes['default'].lower() == "null":
            string = "%s DEFAULT '%s'" % (string, attributes['default'])
        elif 'default' in attributes and attributes['default'].lower() == "null":
            string = "%s DEFAULT NULL" % (string)

        if 'collate' in attributes:
            string = "%s COLLATE %s" % (string, attributes['collate'])

        if 'auto' in attributes:
            string = "%s GENERATED ALWAYS AS IDENTITY" % (string)

        if 'unique' in attributes:
            string = "%s UNIQUE" % (string)

        if 'sequence' in attributes:
            string = "%s NEXTVAL('%s')" % (string, attributes['sequence'])

        return string